import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/toast_util.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class ImageCommonUtil {
  static void saveImage(String url, {Function? callback}) async {
    bool checkPermission = false;
    // 1、读取系统权限的弹框
    if (Platform.isIOS) {
      checkPermission = await Permission.photosAddOnly.request().isGranted;
    } else {
      checkPermission = await Permission.storage.request().isGranted;
    }
    if (checkPermission == true) {
      String dirloc = "";
      if (Platform.isAndroid) {
        dirloc = (await getApplicationSupportDirectory()).path;
      } else {
        dirloc = (await getApplicationDocumentsDirectory()).path;
      }
      int timeTemp = DateTime.now().millisecondsSinceEpoch;
      String path = dirloc + "/" + timeTemp.toString() + ".png";
      Dio dio = Dio()
        ..interceptors.add(
          LogInterceptor(requestBody: true, responseBody: true),
        );
      //设置请求头 不然不能访问资源
      dio.options.headers.addAll({
        HttpHeaders.userAgentHeader: 'ExoPlayer',
      });
      EasyLoading.show(status: '下载中...');
      dio.download(url, path).then((value) {
        LogUtil.v(value.data);
        GallerySaver.saveImage(
          path,
          albumName: timeTemp.toString(),
        ).then((value) {
          EasyLoading.showSuccess('下载成功');
          if (callback != null) {
            callback();
          }
          File(path).deleteSync();
        }).catchError((e) {
          EasyLoading.showError('保存出错');
        }).whenComplete(() {
          EasyLoading.dismiss();
        });
      }).catchError((e) {
        EasyLoading.showError('下载出错');
      });
    } else {
      CustomToast.show('无法存储图片，请先授权！');
    }
  }
}
